import React, { Component } from 'react';
import { partyList } from '../../api/index';
import { ListView } from 'antd-mobile';
import { setImage } from '../../util/imageUtil';
import { calculateStatus as CalculateStatus } from '../../util/StateUtil';
import DateUtil from '../../util/DateUtil';
interface Props {
    offset: number | null;
    limit: number | null;
    query: string;
    maxSize: number;
    coatBody?: React.ReactElement<any>;
    undershirtBody?: React.ReactElement<any>;
    history?: any;
    isCalendar?: boolean;
}
interface State {
    dataSource?: any;
    isLoading?: boolean;
    height?: number;
    hasMore?: boolean;
    dataArray: any[];
    limit: number;
    refreshing: boolean;
    offset: number;
    totalSize: number;
    query: string;
    isCalendar?: boolean;
}
function MyBody(props: any) {
    return <div style={{ margin: '0px 5px 0px 5px' }}>{props.children}</div>;
}
function SmallBody(props: any) {
    return (
        <div style={{ backgroundColor: '#ffffff' }} key={'ccc'}>
            {props.children}
        </div>
    );
}
class index extends Component<Props, State> {
    constructor(props: Props) {
        super(props);

        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1: any, row2: any) => row1 !== row2,
        });

        this.state = {
            offset: 0,
            refreshing: true,
            query: this.props.query || 'isDel = 0 and approval = 1',
            limit: 5,
            totalSize: 0,
            dataSource,
            isLoading: true,
            hasMore: true,
            dataArray: [],
            isCalendar: this.props.isCalendar || false,
        };
    }
    componentDidMount() { }
    // eslint-disable-next-line react/no-deprecated
    componentWillMount() {
        this.loadData();
    }
    componentWillReceiveProps(nextProps: any) {
        if (!!nextProps.query && this.props.query !== nextProps.query) {
            this.setState(
                {
                    dataArray: [],
                    query: nextProps.query,
                    limit: 5,
                    offset: 0,
                },
                () => {
                    this.loadData();
                }
            );
        }
    }
    loadData = () => {
        let then = this;
        const params = {
            offset: this.props.offset || this.state.offset * this.state.limit,
            limit: this.props.limit || this.state.limit,
            query: this.props.query || this.state.query,
        };

        partyList(params).then((response: any) => {
            const list = response.data.partyGroup;
            if (!!list) {
                const dataArr = this.state.dataArray.concat(list);

                let hasMore = true;
                if (dataArr.length >= response.data.totalRecords) {
                    hasMore = false;
                }
                this.setState(
                    {
                        dataArray: dataArr,
                        totalSize: response.data.totalRecords,
                        isLoading: false,
                        hasMore, // 下拉刷新后，重新允许开下拉加载
                        refreshing: false, // 是否在刷新数据
                    },
                    () => {
                        this.state.dataArray.map((a: any, index: number) => {
                            if (!a['image']) {
                                const imageLoad = this.imageLoad;
                                setImage(a, index).then((value: any) => {
                                    let dom = document.getElementById(a.id);
                                    if (dom) {
                                        dom.setAttribute('src', value);
                                    }
                                });
                            }
                        });

                        let dataSource = then.state.dataSource.cloneWithRows(this.state.dataArray);
                        then.setState({
                            dataSource,
                        });
                    }
                );
            } else {
                this.setState({
                    refreshing: false,
                    isLoading: false,
                    hasMore: false,
                });
                return false;
            }
        });
    };
    imageLoad = (image: any, index: number) => {
        this.setState((preState) => {
            const dataArray = preState.dataArray;

            dataArray[index].image = image;
            return {
                dataArray,
            };
        });
    };
    cleanList = (value: any) => {
        this.setState((preState) => {
            const dataArray = value;
            const dataSource = new ListView.DataSource({
                rowHasChanged: (row1: any, row2: any) => row1 !== row2,
            });
            return {
                dataArray,
                dataSource,
            };
        });
    };
    // 滑动到底部时加载更多
    onEndReached = (event: any) => {
        // 加载中或没有数据了都不再加载
        const offset = this.state.offset! + 1;

        if (this.state.isLoading || !this.state.hasMore) {
            return;
        }

        this.setState(
            {
                isLoading: true,
                offset,
            },
            () => {
                this.loadData();
            }
        );
    };
    render() {
        const calculateStatus = CalculateStatus;
        const { history } = this.props;

        const separator = (sectionID: any, rowID: any) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );
        const row = (rowData: any, sectionID: any, rowID: string | number | undefined) => {
            return (
                <div
                    className="thirLi"
                    onClick={() => {
                        history.push(`/party_details/${rowData.principalId}`);
                    }}
                    key={rowData.id}>
                    <a className="actImgArea">
                        <img src={rowData.image} className="sysImg" id={rowData.id} />

                        <div className={'actState actState' + calculateStatus(null, rowData, null).code}></div>
                    </a>
                    <a className="actTit">&nbsp;&nbsp;&nbsp;&nbsp;{rowData.partyName}</a>
                    <div className="actTm">{DateUtil.mergeFormat(rowData.partyStartDate, rowData.partyEndDate)}</div>
                </div>
            );
        };
        return (
            <ListView
                style={{ height: window.innerHeight }}
                dataSource={this.state.dataSource}
                className="am-list sticky-list"
                renderFooter={() => (
                    <div style={{ padding: 30, textAlign: 'center' }}>
                        {this.state.isLoading ? '加载中...' : '加载完毕'}
                    </div>
                )}
                renderRow={(r, s, h) => row(r, s, h)}
                initialListSize={10}
                pageSize={10}
                onEndReachedThreshold={50}
                renderSeparator={separator}
                renderBodyComponent={() => this.props.coatBody || <MyBody />}
                renderSectionBodyWrapper={() => this.props.undershirtBody || <SmallBody />}
                onEndReached={this.onEndReached}
            />
        );
    }
}

export default index;
